package com.book.breakage.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.book.breakage.entity.Accident;
import com.book.breakage.entity.Normal;
import com.book.breakage.service.NormalService;
import com.book.business.entity.BookSell;
import com.book.business.service.BookSellService;
import com.book.common.utils.WareBook;
import com.book.shelves.entity.BookStore;
import com.book.shelves.service.BookStoreService;
import com.book.common.annotation.ControllerEndpoint;
import com.book.common.annotation.Log;
import com.book.common.controller.BaseController;
import com.book.common.entity.FebsConstant;
import com.book.common.entity.FebsResponse;
import com.book.common.entity.QueryRequest;
import com.book.common.utils.FebsUtil;
import com.book.stat.entity.BreakageStat;
import com.book.stat.service.BreakageStatService;
import com.book.warehouse.entity.WarehouseBook;
import com.book.warehouse.service.WarehouseBookService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Author: 张高赫
 * @Description: 20173954
 */

@Controller
public class NormalController extends BaseController {
    @Autowired
    NormalService normalService;
    @Autowired
    BreakageStatService breakageStatService;
    @Autowired
    BookStoreService bookStoreService;
    @Autowired
    WarehouseBookService warehouseBookService;
    @Autowired
    BookSellService bookSellService;

    @GetMapping(FebsConstant.VIEW_PREFIX + "breakage/normal")
    public String normalIndex() {
        return FebsUtil.view("breakage/normal/normalList");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "breakage/normal/add")
    public String normalAdd() {
        return FebsUtil.view("breakage/normal/normalAdd");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "breakage/normal/update/{id}")
    public String normalUpdate(@PathVariable Integer id, ModelMap modelMap) {
        Normal normal = normalService.getById(id);
        modelMap.addAttribute("normal", normal);
        return FebsUtil.view("breakage/normal/normalUpdate");
    }

    @GetMapping("normal")
    @ResponseBody
    @RequiresPermissions("normal:view")
    public FebsResponse findNormal(Normal normal) {
        return new FebsResponse().success().data(normalService.normalList(normal));
    }

    @Log("访问正常报损")
    @GetMapping("normal/list")
    @ResponseBody
    @RequiresPermissions("normal:view")
    public FebsResponse normalList(QueryRequest request, Normal normal) {
        Map<String, Object> dataTable = getDataTable(this.normalService.normalPage(request, normal));
        return new FebsResponse().success().data(dataTable);
    }

    @Log("正常报损-新增")
    @PostMapping("normal")
    @ResponseBody
    @RequiresPermissions("normal:add")
    @ControllerEndpoint(operation = "报损新增", exceptionMessage = "新增报损信息失败")
    public FebsResponse normalAdd(Normal normal) {
        WarehouseBook warehouseBook = warehouseBookService.getOne(new QueryWrapper<WarehouseBook>().lambda()
                .eq(WarehouseBook::getBookname, normal.getBookname())
                .eq(WarehouseBook::getPutaway, "1"));
        if (warehouseBook == null) {
            return new FebsResponse().message("抱歉仓库没有该书籍。");
        }
        WareBook.wareBookChange(warehouseBook.getBookname(), "减少", normal.getNumber());
        normal.setStatus("3")
                .setBooktype(warehouseBook.getType())
                .setBookmoney(warehouseBook.getBookmoney())
                .setPubid(warehouseBook.getPurchasefactory())
                .setUsername(getCurrentUser().getUsername())
                .setTotalmoney(warehouseBook.getBookmoney() * normal.getNumber())
                .setBreakagedate(new Date());
        this.normalService.normalAdd(normal);
        return new FebsResponse().success();
    }

    @Log("正常报损-修改")
    @PostMapping("normal/update")
    @ResponseBody
    @RequiresPermissions("normal:update")
    @ControllerEndpoint(operation = "修改报损信息成功", exceptionMessage = "修改报损信息失败")
    public FebsResponse normalUpdate(Normal normal) {
        Normal byId = normalService.getById(normal.getId());
        if ("3".equals(byId.getStatus())) {
            return new FebsResponse().message("管理员手动添加报损，不能操作！");
        }
        this.normalService.normalUpdate(normal);
        return new FebsResponse().success();
    }

    @Log("正常报损-删除")
    @PostMapping("normal/delete/{ids}")
    @ResponseBody
    @RequiresPermissions("normal:delete")
    @ControllerEndpoint(operation = "删除报损成功", exceptionMessage = "删除报损信息失败")
    public FebsResponse normalDelete(@PathVariable String ids) {
        String[] arr = ids.split(",");
        List<Normal> normalList = normalService.normalApply(arr);
        for (int i = 0; i < normalList.size(); i++) {
            if ("0".equals(normalList.get(i).getStatus())) {
                return new FebsResponse().message("报损申请还未进行审批，不能删除！");
            }
            if ("3".equals(normalList.get(i).getStatus())) {
                return new FebsResponse().message("管理员手动添加报损，不能操作！");
            }
            this.normalService.normalDelete(arr);
        }
        return new FebsResponse().success();
    }

    @Log("正常报损-审批")
    @PostMapping("normal/apply/{ids}")
    @ResponseBody
    @RequiresPermissions("normal:apply")
    @ControllerEndpoint(operation = "报损审批成功", exceptionMessage = "报损审批失败")
    public FebsResponse normalApply(@PathVariable String ids) {
        String[] arr = ids.split(",");
        List<Normal> normalList = normalService.normalApply(arr);
        for (int i = 0; i < normalList.size(); i++) {
            if ("1".equals(normalList.get(i).getStatus())) {
                return new FebsResponse().message("该条报损信息，已经通过，请勿重复操作！");
            }
            if ("2".equals(normalList.get(i).getStatus())) {
                return new FebsResponse().message("该条报损信息，已驳回，不能进行审批！");
            }
            if ("3".equals(normalList.get(i).getStatus())) {
                return new FebsResponse().message("管理员手动添加报损，不能操作！");
            }
            normalList.get(i).setStatus("1");
            normalService.normalUpdate(normalList.get(i));
            breakageStatService.update(new UpdateWrapper<BreakageStat>().lambda()
                    .eq(BreakageStat::getBreakageid, normalList.get(i).getBreakageid())
                    .set(true, BreakageStat::getOmit, "1"));
            BookStore bookStore = bookStoreService.getOne(new QueryWrapper<BookStore>().lambda()
                    .eq(BookStore::getBookname, normalList.get(i).getBookname())
                    .eq(BookStore::getFlag, "1"));
            if (bookStore.getNum() == normalList.get(i).getNumber()) {
                bookStoreService.removeById(bookStore.getId());
            } else {
                bookStore.setNum(bookStore.getNum() - normalList.get(i).getNumber());
                bookStoreService.updateBookStore(bookStore);
            }
        }
        return new FebsResponse().success();
    }

    @Log("正常报损-驳回")
    @PostMapping("normal/no/{id}")
    @ResponseBody
    @RequiresPermissions("normal:no")
    @ControllerEndpoint(operation = "成功驳回", exceptionMessage = "驳回失败")
    public FebsResponse normalNo(@PathVariable String id) {
        Normal normal = normalService.getById(id);
        if ("1".equals(normal.getStatus())) {
            return new FebsResponse().message("该条报损申请，已通过，不能进行驳回！");
        }
        if ("2".equals(normal.getStatus())) {
            return new FebsResponse().message("该条报损申请，已被驳回，请勿重复操作！");
        }
        if ("3".equals(normal.getStatus())) {
            return new FebsResponse().message("管理员手动添加报损，不能操作！");
        }
        normal.setStatus("2");
        normalService.normalUpdate(normal);
        BreakageStat breakageStat = breakageStatService.getOne(new QueryWrapper<BreakageStat>().lambda().eq(BreakageStat::getBreakageid, normal.getBreakageid()));
        if (breakageStat != null) {
            breakageStatService.removeById(breakageStat.getId());
        }
        WareBook.wareBookChange(normal.getBookname(),"增加",normal.getNumber());
        WarehouseBook warehouseBookServiceOne = warehouseBookService.getOne(new QueryWrapper<WarehouseBook>().lambda()
                .eq(WarehouseBook::getBookname, normal.getBookname()).eq(WarehouseBook::getPutaway, "1"));
        if (warehouseBookServiceOne == null) {
            bookStoreService.remove(new QueryWrapper<BookStore>().lambda()
                    .eq(BookStore::getBookname, normal.getBookname()).notIn(BookStore::getFlag, "1"));
            bookSellService.remove(new QueryWrapper<BookSell>().lambda().eq(BookSell::getBookname, normal.getBookname()));
        }
        BookStore bookStore = bookStoreService.getOne(new QueryWrapper<BookStore>().lambda()
                .eq(BookStore::getBookname, normal.getBookname())
                .eq(BookStore::getFlag, "1"));
        if (bookStore.getNum() == normal.getNumber()) {
            bookStoreService.removeById(bookStore.getId());
        } else {
            bookStore.setNum(bookStore.getNum() - normal.getNumber());
            bookStoreService.updateBookStore(bookStore);
        }
        return new FebsResponse().success();
    }
}
